package com.plum.admin.common.limit;

import com.plum.admin.common.constant.Constant;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * TODO
 *
 * @author 子丶沫
 * @version 1.0
 * @date 2021/9/28 9:55
 */
@Component
@Slf4j
public class RedisRateLimiter {

    @Autowired
    private RedissonClient redisson;

    public boolean redisAcquire(String name,Long rate,Long rateInterval){
        boolean token;
       try{
           RRateLimiter rateLimiter = redisson.getRateLimiter(Constant.LIMIT_PRE + name);
           rateLimiter.trySetRate(RateType.OVERALL,rate,rateInterval, RateIntervalUnit.MILLISECONDS);
           token=rateLimiter.tryAcquire();
           rateLimiter.expireAsync(rateInterval*2, TimeUnit.MILLISECONDS);
       }catch (Exception e){
           token=true;
       }
       return token;
    }
}
